package com.fast.cron.common.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: Leo Jie
 * @date: 2018-10-07 21:34
 * @version: v1.0
 */
public class JsonUtils {
    private static final String ENCODING = "UTF-8";
    private static SerializerFeature[] features = new SerializerFeature[]{
            SerializerFeature.WriteMapNullValue,
            SerializerFeature.WriteNullBooleanAsFalse,
            SerializerFeature.WriteNullListAsEmpty,
            SerializerFeature.WriteNullNumberAsZero,
            SerializerFeature.WriteNullStringAsEmpty,
            SerializerFeature.WriteDateUseDateFormat
    };

    private static String toJSONString(Object object) {
        return JSON.toJSONString(object, features);
    }

    public static void json(HttpServletResponse response, Object data, String encoding) {
        response.setContentType("text/plain;charset=" + encoding);
        response.setCharacterEncoding(encoding);
        PrintWriter out;
        try {
            out = response.getWriter();
            out.write(toJSONString(data));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void json(HttpServletResponse response, Object data) {
        json(response, data, ENCODING);
    }

}  